/**
 * 
 */
package com.qdairlines.common;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qdairlines.constant.BaseConsts;
import com.qdairlines.constant.Select2Consts;
import com.qdairlines.entity.dict.Select2;

/**
 * @author pangyannan
 * @date 2017年4月11日
 * @company QingDao Airlines
 * @description select2插件的工具类
 */
public class Select2Util {
	private static final Logger logger = LoggerFactory.getLogger(Select2Util.class);
	
	/**
	 * 将list对象转换为select2需要的json对象，如果没有数据，则返回用户 无查询结果 的提示
	 * @param list
	 * @param valueName
	 * @param lableName
	 * @return
	 */
	public static <T> String  toJosn(List<T> list,String valueName,String lableName){
		List<Select2> select2List = new ArrayList<>();
		if(list !=null && list.size()>0){
			
			 for(T t: list){
				 
				 Select2 select2 = new Select2();
				 
				 String id = null;
				 String text = null;
				try {
					id = BeanUtils.getProperty(t,valueName).toString();
					text = BeanUtils.getProperty(t,lableName).toString();
				} catch (IllegalAccessException e) {
					TraceUtil.error(logger, e);
				} catch (InvocationTargetException e) {
					TraceUtil.error(logger, e);
				} catch (NoSuchMethodException e) {
					TraceUtil.error(logger, e);
				}
				 
				 select2.setId(id);
				 select2.setText(text);
				 select2List.add(select2); 
			 }
		
		}else{
//			 Select2 select2 = new Select2();
//			 select2.setId(BaseConsts.EMPTY_STRING);
//			 select2.setText(Select2Consts.EMPTY_MSG);
//			 select2List.add(select2);
		}
		
		Map<String,Object > map = new HashMap<>();
		map.put("items", select2List);
		map.put("itemsCount", select2List.size());
		return  JSONObject.fromObject(map).toString();
	}
	
	/**
	 * 返回未查询到数据的提示
	 * @return
	 */
	public static String getEmptyJson() {
		Select2 select2 = new Select2();
		select2.setId(BaseConsts.EMPTY_STRING);
		select2.setText(Select2Consts.EMPTY_MSG);

		List<Select2> select2List = new ArrayList<>();
		select2List.add(select2);

		Map<String, Object> map = new HashMap<>();
		map.put("items", select2List);
		map.put("itemsCount", select2List.size());
		return JSONObject.fromObject(map).toString();
	}
	

}
